package com.cqcetbbs.smartlab.cqcetbbs.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cqcetbbs.smartlab.cqcetbbs.R;
import com.cqcetbbs.smartlab.cqcetbbs.adapter.ArtlistApadter;
import com.cqcetbbs.smartlab.cqcetbbs.javabean.ArtlistInfos;
import com.cqcetbbs.smartlab.cqcetbbs.utils.DensityUtil;
import com.cqcetbbs.smartlab.cqcetbbs.utils.MySnackbar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by user on 2017/10/24.
 * 交流学习
 */

public class CommunicationActivity extends Activity {
    private static final int ARTLISTINFO_SUCCESS_MORE = 3;
    View itemview;

    //文章(分类)列表
    private static final String ARTLISTINFO_URL = "http://api.cqcetlab.com/Home/article/artlist";
    private static final int ARTLISTINFO_SUCCESS = 1;
    private static final int ARTLISTINFO_ERROR = 2;

    String strtype = "";
    private IndicatorViewPager indicatorViewPager;
    GridView gv_photo;
    private OkHttpClient client;
    private Type listType;
    Gson gson;
    String url_type = "notice";
    int pagenotice = 2;
    int pagelife = 2;
    int pageclub = 2;
    int pagestudy = 2;
    int pagetrade = 2;
    int pagejob = 2;
    RefreshLayout refresh;
    LinearLayout search_ll;
    ArtlistApadter Apadter0;
    ArtlistApadter Apadter1;
    ArtlistApadter Apadter2;
    ArtlistApadter Apadter3;
    ArtlistApadter Apadter4;
    ArtlistApadter Apadter5;

    LinearLayout ll_not_net;
    boolean iserrror = true;
    ProgressDialog dialog;
    List<ArtlistInfos.ArtlistInfo> ArtlistInfoList;
    private Map<String, List<ArtlistInfos.ArtlistInfo>> AllData;
    ArtlistInfos ArtlistInfos;
    List<ArtlistInfos.ArtlistInfo> data;
    RefreshLayout refreshLayout;
    ListView listView;
    private String[] type = {"notice", "life", "club", "study", "trade", "job"};
    String page = "0";
    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case ARTLISTINFO_SUCCESS:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    indicatorViewPager.setAdapter(new MyAdapter());
                    if (refreshLayout != null) {
                        refreshLayout.finishRefresh();
                    }
                    break;
                case ARTLISTINFO_ERROR:

                    if (dialog != null) {
                        dialog.dismiss();
                    }

                    if (listView != null) {
                        MySnackbar.ShowSnackbar(listView, "网络异常");
                    } else {
                        if (!iserrror) {
                            iserrror = true;
                            ll_not_net.setVisibility(View.VISIBLE);
                            Toast.makeText(CommunicationActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                        }
                    }
                    if (refresh != null) {
                        refresh.finishRefresh();
                    }
                    break;
                case ARTLISTINFO_SUCCESS_MORE:
                    if (refresh != null) {
                        refresh.finishRefresh();
                    }
                    Apadter0.notifyDataSetChanged();
                    if (null != Apadter1) {
                        Apadter1.notifyDataSetChanged();
                    }
                    if (null != Apadter2) {
                        Apadter2.notifyDataSetChanged();
                    }
                    if (null != Apadter3) {
                        Apadter3.notifyDataSetChanged();
                    }
                    if (null != Apadter4) {
                        Apadter4.notifyDataSetChanged();
                    }
                    if (null != Apadter5) {
                        Apadter5.notifyDataSetChanged();
                    }

                    break;
            }

        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_communication);

        search_ll = findViewById(R.id.search_ll);
        ll_not_net = findViewById(R.id.ll_not_net);
        ll_not_net.setVisibility(View.GONE);

        initPro();

        ViewPager viewPager = findViewById(R.id.moretab_viewPager);
        ScrollIndicatorView scrollIndicatorView = findViewById(R.id.moretab_indicator);

        float unSelectSize = 12;
        float selectSize = unSelectSize * 1.3f;
        scrollIndicatorView.setOnTransitionListener(new OnTransitionTextListener().setColor(0xFF2196F3, Color.GRAY).setSize(selectSize, unSelectSize));

        scrollIndicatorView.setScrollBar(new ColorBar(this, 0xFF2196F3, 4));

        viewPager.setOffscreenPageLimit(2);
        indicatorViewPager = new IndicatorViewPager(scrollIndicatorView, viewPager);


        AllData = new HashMap<String, List<ArtlistInfos.ArtlistInfo>>();
        gson = new Gson();
        listType = new TypeToken<ArrayList<ArtlistInfos.ArtlistInfo>>() {
        }.getType();

        //请求网络
        postData();

        search_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CommunicationActivity.this, SearchActivity.class);
                Bundle bundle = new Bundle();
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    private void initPro() {

        dialog = new ProgressDialog(CommunicationActivity.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        dialog.setCancelable(false);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        // 设置提示的title的图标，默认是没有的，如果没有设置title的话只设置Icon是不会显示图标的
        dialog.setMessage("数据加载中。。。");

    }

    private class MyAdapter extends IndicatorViewPager.IndicatorViewPagerAdapter {
        private String[] versions = {"公告", "生活", "社团", "学习", "交易", "工作"};
        private String[] names = {"公告", "生活", "社团", "学习", "交易", "工作"};

        @Override
        public int getCount() {
            return versions.length;
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            TextView textView = new TextView(CommunicationActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            //lp.gravity = Gravity.CENTER;
            textView.setLayoutParams(lp);


            textView.setGravity(Gravity.CENTER);
            textView.setText(versions[position]);
            textView.setPadding(DensityUtil.dip2px(CommunicationActivity.this, 30), 0, DensityUtil.dip2px(CommunicationActivity.this, 30), 0);
            return textView;
        }

        @Override
        public View getViewForPage(final int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                itemview = View.inflate(CommunicationActivity.this, R.layout.artlistinfo_layout, null);
                listView = itemview.findViewById(R.id.listview);
                refreshLayout = itemview.findViewById(R.id.refreshLayout);
                refreshLayout.setEnableAutoLoadmore(false);

                //设置主题
                CommunicationActivity.this.setThemeColor(refreshLayout, R.color.colorPrimary, R.color.colorPrimary);
                //ListView view = new ListView(container.getContext());
                switch (position) {
                    case 0:
                        data = AllData.get("notice");
                        Apadter0 = new ArtlistApadter(CommunicationActivity.this, data);
                        listView.setAdapter(Apadter0);
                        setonItemclick(listView, data);
                        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                            @Override
                            public void onRefresh(RefreshLayout refreshlayout) {
                                //Toast.makeText(getApplicationContext(),"刷新了notice",Toast.LENGTH_SHORT).show();
                                // refreshlayout.finishRefresh(1500,false);
                                pagenotice++;
                                postmoreData("notice", "5", pagenotice + "", refreshlayout);
                            }
                        });
                        convertView = itemview;
                        break;
                    case 1:
                        data = AllData.get("life");
                        Apadter1 = new ArtlistApadter(CommunicationActivity.this, data);
                        listView.setAdapter(Apadter1);
                        setonItemclick(listView, data);
                        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                            @Override
                            public void onRefresh(RefreshLayout refreshlayout) {

                                refreshlayout.finishRefresh(1500, false);
                                pagelife++;
                                postmoreData("life", "5", pagelife + "", refreshlayout);

                            }
                        });
                        convertView = itemview;
                        break;
                    case 2:
                        data = AllData.get("club");
                        Apadter2 = new ArtlistApadter(CommunicationActivity.this, data);
                        listView.setAdapter(Apadter2);
                        setonItemclick(listView, data);

                        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                            @Override
                            public void onRefresh(RefreshLayout refreshlayout) {
                                //Toast.makeText(getApplicationContext(),"刷新了notice",Toast.LENGTH_SHORT).show();
                                refreshlayout.finishRefresh(1500, false);
                                pageclub++;
                                postmoreData("club", "5", pageclub + "", refreshlayout);
                            }
                        });
                        convertView = itemview;

                        break;
                    case 3:
                        data = AllData.get("study");
                        Apadter3 = new ArtlistApadter(CommunicationActivity.this, data);
                        listView.setAdapter(Apadter3);
                        setonItemclick(listView, data);


                        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                            @Override
                            public void onRefresh(RefreshLayout refreshlayout) {
                                //Toast.makeText(getApplicationContext(),"刷新了notice",Toast.LENGTH_SHORT).show();
                                refreshlayout.finishRefresh(1500, false);
                                pagestudy++;
                                postmoreData("study", "5", pagestudy + "", refreshlayout);
                            }
                        });
                        convertView = itemview;
                        break;
                    case 4:
                        data = AllData.get("trade");
                        Apadter4 = new ArtlistApadter(CommunicationActivity.this, data);
                        listView.setAdapter(Apadter4);
                        setonItemclick(listView, data);

                        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                            @Override
                            public void onRefresh(RefreshLayout refreshlayout) {
                                //Toast.makeText(getApplicationContext(),"刷新了notice",Toast.LENGTH_SHORT).show();
                                refreshlayout.finishRefresh(1500, false);
                                pagetrade++;
                                postmoreData("trade", "5", pagetrade + "", refreshlayout);
                            }
                        });

                        convertView = itemview;
                        break;
                    case 5:

                        data = AllData.get("job");
                        Apadter5 = new ArtlistApadter(CommunicationActivity.this, data);
                        listView.setAdapter(Apadter5);
                        setonItemclick(listView, data);

                        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                            @Override
                            public void onRefresh(RefreshLayout refreshlayout) {
                                //Toast.makeText(getApplicationContext(),"刷新了notice",Toast.LENGTH_SHORT).show();
                                refreshlayout.finishRefresh(1500, false);
                                pagejob++;
                                postmoreData("job", "5", pagejob + "", refreshlayout);
                                // refreshLayout.finishRefresh();
                            }
                        });
                        convertView = itemview;
                        break;

                }
            }


            return convertView;
        }

        @Override
        public int getItemPosition(Object object) {
            //这是ViewPager适配器的特点,有两个值 POSITION_NONE，POSITION_UNCHANGED，默认就是POSITION_UNCHANGED,
            // 表示数据没变化不用更新.notifyDataChange的时候重新调用getViewForPage
            return PagerAdapter.POSITION_UNCHANGED;
        }
//        private int getTextWidth(TextView textView) {
//            if (textView == null) {
//                return 0;
//            }
//            Rect bounds = new Rect();
//            String text = textView.getText().toString();
//            Paint paint = textView.getPaint();
//            paint.getTextBounds(text, 0, text.length(), bounds);
//            int width = bounds.left + bounds.width();
//            return width;
//        }


    }

    //post请求后台数据（默认加载五条数据）
    private void postData() {
        try {
            dialog.show();
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        client = new OkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < type.length; i++) {
                    RequestBody body = new FormBody.Builder()
                            .add("type", type[i])
                            .build();
                    final Request request = new Request.Builder()
                            .post(body)
                            .url(ARTLISTINFO_URL)
                            .build();
                    //新建一个线程，用于得到服务器响应的参数
                    Response response = null;
                    try {
                        //回调
                        response = client.newCall(request).execute();
                        if (response.isSuccessful()) {
                            //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                            String Data = response.body().string();
                            //SpUtils.setStringValues(CommunicationActivity.this, "ArtlistInfo_data", Data);

                            ArtlistInfos = gson.fromJson(Data, ArtlistInfos.class);
                            AllData.put(type[i], ArtlistInfos.getData());

                            if (i == type.length - 1) {
                                Message msg = mhandler.obtainMessage(ARTLISTINFO_SUCCESS, Data);
                                mhandler.sendMessage(msg);
                            }
                        }
                    } catch (IOException e) {
                        iserrror = false;
                        Message msg = mhandler.obtainMessage(ARTLISTINFO_ERROR);
                        mhandler.sendMessage(msg);
                    }
                }
            }
        }).start();
    }


    // post请求后台数据（默认加载五条数据）
    private void postmoreData(String type, final String num, final String page, RefreshLayout refreshlayout) {
        client = new OkHttpClient();
        url_type = type;
        refresh = refreshlayout;
        new Thread(new Runnable() {
            @Override
            public void run() {
                RequestBody body = new FormBody.Builder()
                        .add("type", url_type)
                        .add("num", num)
                        .add("page", page)
                        .build();
                final Request request = new Request.Builder()
                        .post(body)
                        .url(ARTLISTINFO_URL)
                        .build();
                //新建一个线程，用于得到服务器响应的参数
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        String Data = response.body().string();
                        //SpUtils.setStringValues(CommunicationActivity.this, "ArtlistInfo_data", Data);
                        ArtlistInfos ArtlistInfosMore= gson.fromJson(Data, ArtlistInfos.class);
                        List<ArtlistInfos.ArtlistInfo> artlistInfos = AllData.get(url_type);
                        artlistInfos.addAll(0, ArtlistInfosMore.getData());
                        Message msg = mhandler.obtainMessage(ARTLISTINFO_SUCCESS_MORE, refresh);
                        mhandler.sendMessage(msg);
                    }
                } catch (IOException e) {

                    Message msg = mhandler.obtainMessage(ARTLISTINFO_ERROR, refresh);
                    mhandler.sendMessage(msg);

                }
            }
        }).start();
    }

    public void setonItemclick(ListView list, final List<ArtlistInfos.ArtlistInfo> data) {
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Bundle bundle = new Bundle();
                bundle.putString("id", data.get((int) l).getId() + "");
                Intent intent = new Intent(CommunicationActivity.this, NewsDetailActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }


    private void setThemeColor(RefreshLayout refreshLayout, int colorPrimary, int colorPrimaryDark) {
        refreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.white);
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setStatusBarColor(ContextCompat.getColor(this, colorPrimaryDark));
        }
    }
}
